import json
from datetime import datetime
from common.log import Logs
from common.http import render_json, handle_record_operate
from {app_name}.models import {model_table}

log = Logs(__name__).get_logger()


@handle_record_operate(method="add {table_name}")
def add_{table_name}(request):
    if not request.method == "POST":
        return render_json("Please use POST request", code=1)
    json_str = request.body
    if not json_str:
        return render_json("Please give me json")
    json_obj = json.loads(json_str)
    log.info(f'request add_{table_name}, request user: {request.user.user_name}')
    log.info(f'add_{table_name} params: {json_obj}')
    try:
        {model_table}.objects.create(**json_obj, creator=request.user.user_name)
        return render_json('Create {model_table} successful!')
    except Exception as e:
        log.error(f"-----Create {model_table} error is: {e}")
        return render_json('Sorry, Server is busy!')


@handle_record_operate(method="delete {table_name}")
def del_{table_name}(request, id):
    if not request.method == "DELETE":
        return render_json("Please use DELETE request!", code=1)
    log.info(f'request del_{table_name}, request user: {request.user.user_name}')
    log.info(f'del_{table_name} id: {id}')
    try:
        {model_table}.objects.filter(id=id).delete()
        return render_json('Delete {model_table} successful!')
    except Exception as e:
        log.error(f"-----Delete {model_table} error: {e}")
        return render_json('Sorry,server is busy!', code=1)


@handle_record_operate(method="update {table_name}")
def update_{table_name}(request, id):
    if not request.method == "PATCH":
        return render_json(f"Please use PATCH request, The url:user/update_{table_name}/{id}", code=1)
    json_str = request.body
    if not json_str:
        return render_json("Please give me json")
    json_obj = json.loads(json_str)
    log.info(f'request update_{table_name}, request user: {request.user.user_name}')
    log.info(f'update_{table_name} params: {json_obj}')
    log.info(f'update_{table_name} id: {id}')
    try:
        {model_table}.objects.filter(id=id).update(**json_obj, update_at=datetime.now(), updater=request.user.user_name)
        return render_json('Update success!')
    except Exception as e:
        log.error(f"-----update_{table_name} error is: {e}")
        return render_json('Sorry,server is busy!', code=1)


@handle_record_operate(method="get {table_name} list")
def get_{table_name}_list(request):
    if not request.method == "POST":
        return render_json("Please use POST request!", code=1)
    json_str = request.body
    if not json_str:
        return render_json("Please give me json")
    json_obj = json.loads(json_str)
    log.info(f'request get_{table_name}_list, request user: {request.user.user_name}')
    log.info(f'get_{table_name}_list params: {json_obj}')
    offset = json_obj['offset']
    limit = json_obj['size'] + offset
    try:
        filter_args = {}
        for key, value in json_obj['filter_field'].items():
            if value != '':
                if "at" in key:
                    if len(value) == 2:
                        key = key + "__range"
                else:
                    key = key + "__icontains"
                filter_args[key] = value
        log.info(f"filter_args: {filter_args}")
        if filter_args:
            res = {model_table}.objects.filter(**filter_args).order_by('-id')
        else:
            res = {model_table}.objects.all().order_by('-id')
        count = res.count()
        data_list = [i.to_dict() for i in res[offset:limit]]
        data = {"totalCount": count, "list": data_list}
        return render_json(data=data)
    except Exception as e:
        log.error(f"-----Get {table_name} list error: {e}")
        return render_json('Sorry, server is busy!', code=1)

